package com.daxia.bumall.web.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.common.DesignStatus;
import com.daxia.bumall.common.Logs;
import com.daxia.bumall.common.RecommonStatus;
import com.daxia.bumall.dto.BrandDTO;
import com.daxia.bumall.dto.BrandStyleDTO;
import com.daxia.bumall.dto.DesignDTO;
import com.daxia.bumall.dto.DesignProductDTO;
import com.daxia.bumall.dto.HardcoverQueryDTO;
import com.daxia.bumall.dto.ProductDTO;
import com.daxia.bumall.model.Brand;
import com.daxia.bumall.model.HouseStyle;
import com.daxia.bumall.model.ProductCategory;
import com.daxia.bumall.model.ProductProperties;
import com.daxia.bumall.model.Specification;
import com.daxia.bumall.support.Page;

@Controller
@RequestMapping(value = "staybag", produces = "text/html;charset=UTF-8")
public class StayBagController extends BaseController {
	
	@RequestMapping("/index")
	public String index(BrandStyleDTO brandStyleDTO, Page page,Integer pageNum, Map<String, Object> map) {
		prepareCategories(map);
		/**
		 * 品牌家居
		 */
		page.setPageSize(8);
		brandStyleDTO.setRecommon(RecommonStatus.Recommened.getValue());
		List<BrandStyleDTO> brandStyleDTOs = brandStyleService.find(brandStyleDTO, page);
		map.put("brandStyleDTOs", brandStyleDTOs);
		Logs.COMMON.debug(brandStyleDTOs.size());
    	map.put("page", page);
    	map.put("brandStyleDTO", brandStyleDTO);
    	//map.put("houseStyles", houseStyleService.findAll());
    	map.put("houseStyles", houseStyleService.findDistinctStyleFromBrand(new BrandStyleDTO()));
    	/**
    	 * 相关方案
    	 */
    	Page page2=new Page();
    	if(pageNum!=null){
    		page2.setPage(pageNum);
    	}else{
    		page2.setPage(1);
    	}
    	page2.setPageSize(6);
    	DesignDTO designDTO=new DesignDTO();
    	if(brandStyleDTO!=null&&brandStyleDTO.getStyleID()!=null&&brandStyleDTO.getStyleID()!=0){
    		HouseStyle hs=new HouseStyle();
        	hs.setId(brandStyleDTO.getStyleID());
        	designDTO.setHouseStyle(hs);
    	}
//    	designDTO.setRecommend(RecommonStatus.Recommened.getValue());  //是否推荐的方案
    	List<DesignDTO> designDTOs=designService.find(designDTO, page2);
    	map.put("designDTOs",designDTOs );
    	map.put("page2", page2);

		return "staybag/staybag_index";
	}
	
	@RequestMapping("/detail")
	public String detail(Long brandID, Long styleID, Integer sortType, HardcoverQueryDTO query, Page page, Integer pageNum, Map<String, Object> map) {
		prepareCategories(map);
		BrandDTO brandDTO = brandService.load(brandID);
		
		ProductDTO productQuery = new ProductDTO();
		Brand brandQuery = new Brand();
		brandQuery.setId(brandDTO.getId());
		productQuery.setBrand(brandQuery);
		productQuery.setSortType(sortType);
		if (query.getCategoryID() != null) {
			ProductCategory productCategory = new ProductCategory();
			productCategory.setId(query.getCategoryID());
			productQuery.setProductCategory(productCategory );
		}
		
		ProductDTO productQuery2 = new ProductDTO();
		productQuery2.setBrand(brandQuery);
		
		Page page2 = new Page();
		if (pageNum == null) {
			pageNum = 1;
		}
		page2.setPage(pageNum);
		
		Set<ProductCategory> productCategorys = new HashSet<ProductCategory>();
		List<ProductDTO> productDTOs = productService.find(productQuery, page2);
		List<ProductDTO> productCategoryDTOs = productService.find(productQuery2, null);

		for (ProductDTO productDTO : productCategoryDTOs) {
			ProductCategory productCategory = productDTO.getProductCategory();
			productCategorys.add(productCategory);
		}
		
		DesignProductDTO desiginProductQuery = new DesignProductDTO();
		List<DesignProductDTO> designProductDTOs = designProductService.find(desiginProductQuery , null);
		Set<Long> designIDs = new HashSet<Long>();
		for (DesignProductDTO designProductDTO : designProductDTOs) {
			designIDs.add(designProductDTO.getDesign().getId());
		}
		page.setTotalRecords(designIDs.size());
		
		//设置推荐的品牌
		ProductDTO queryProduct = new ProductDTO();
		brandQuery.setRecommend(RecommonStatus.Recommened.getValue());
		queryProduct.setBrand(brandQuery);
		desiginProductQuery.setProduct(queryProduct);
		//设置通过审核的方案
		DesignDTO queryDesign=new DesignDTO();
		queryDesign.setStatus(DesignStatus.Pass.getValue());
		desiginProductQuery.setDesign(queryDesign);
		
		List<DesignDTO> designs = designProductService.findDistictDesigns(desiginProductQuery, null);
		
		
		map.put("productCategorys", productCategorys);
		map.put("brandDTO", brandDTO);
		map.put("productDTOs", productDTOs);
		map.put("totalProduct", page2.getTotalRecords());  
		map.put("totalDesign", page.getTotalRecords());
		map.put("brandID", brandID);
		map.put("styleID", styleID);
		map.put("designProductDTOs", designProductDTOs);
    	map.put("page", page);
    	map.put("totalDesignProduct", designProductDTOs.size());
    
    	map.put("page2", page2);
    	map.put("query", query);
    	map.put("sortType", sortType);
    	
    	if(designs == null) {
    		map.put("totalDesigns",0);
    	} else {
    		map.put("totalDesigns",designs.size());
    	}
    	map.put("designs", designs);

		/**
    	 * 产品类目图片，此处先说明，页面上要进行对应的图片切换，图片包括：产品图片+各类类目图片，根据
    	 * 类目切换来显示不同类目的对应图片，产品的图片还是不变
    	 */
    	map.put("categories", productCategoryService.findAllRoot());
		return "staybag/staybag_detail";
	}
	
	@ResponseBody
	@RequestMapping("getBrands")
	public String getBrands() throws Exception {
		List<BrandDTO> brands = brandService.findRecommended();
		JSONArray array = new JSONArray();
		for (BrandDTO b : brands) {
			JSONObject j = new JSONObject();
			j.put("name", b.getName());
			j.put("id", b.getId());
			array.add(j);
		}
		return array.toJSONString();
	}
	
	@ResponseBody
	@RequestMapping("getProducts")
	public String getProducts(Long styleID, Long brandID, Long categoryID, Integer sortType, Page page) throws Exception {
		ProductDTO query = new ProductDTO();
		if (brandID != null) {
			query.setBrand(new Brand());
			query.getBrand().setId(brandID);
		}
		//query.setOrderBy(orderBy);
		//if (StringUtils.isNotBlank(style)) {
			//query.setStyle(style.replace("风格", ""));
		//}
		if (styleID != null && styleID > 0) {
			query.setStyle(houseStyleService.load(styleID).getName().replace("风格", ""));
		}
		if (sortType == null) {
			sortType = 1;
		}
		if (sortType == 1) {
			// 综合
			query.setOrderBy(" rand() ");
		} else if (sortType == 2) {
			// 销量
			query.setOrderBy("p.totalSold desc");
		} else if (sortType == 3) {
			// 价格
			query.setOrderBy("sellingPrice asc");
		}
		
		
		
		query.setProductCategory(new ProductCategory());
		query.getProductCategory().setId(categoryID);
		List<ProductDTO> products = productService.findForOnlineDesign(query, page);
		JSONObject json = new JSONObject();
		json.put("totalRecords", page.getTotalRecords());
		json.put("totalPages", page.getTotalPages());
		JSONArray array = new JSONArray();
		for (ProductDTO p : products) {
			JSONObject jP = new JSONObject();
			jP.put("name", p.getName());
			jP.put("id", p.getId());
			jP.put("image", p.getFirstSpec().getImages().split(",")[0]);
			JSONArray specArr = new JSONArray();
			for (Specification sp : p.getSpecifications()) {
				JSONObject j = new JSONObject();
				j.put("id", sp.getId());
				j.put("ogCode", sp.getOgCode());
				j.put("spec1", sp.getSpec1());
				j.put("spec2", sp.getSpec2());
				j.put("image", sp.getImages().split(",")[0]);
				j.put("realPrice", sp.getRealPrice());
				for (ProductProperties pp : sp.getProductProperties()) {
					if ("风格".equals(pp.getName())) {
						j.put("style", pp.getValue());
					}
					if ("材质".equals(pp.getName())) {
						j.put("material", pp.getValue());
					}
					if ("颜色".equals(pp.getName())) {
						j.put("color", pp.getValue());
					}
				}
				specArr.add(j);
			}
			jP.put("specs", specArr);
			jP.put("specIndex", 0);
			array.add(jP);
		}
		json.put("data", array);
		return json.toJSONString();
	}
	
}
